package file;

import java.io.*;
import java.util.Scanner;

/**
 * 文件流的使用
 */
public class FileStream {
    //写入文件
    public static void main(String[] args) throws IOException {
        OutputStream op = new FileOutputStream("file1.txt");
        //写入
        op.write('1');

        byte[] bs = {(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd'};
        //刷新
        op.write(bs);

        String s = "ssss";

        byte[] bytes = s.getBytes("utf-8");

        op.write(bytes);

        op.flush();

        OutputStreamWriter osw = new OutputStreamWriter(op, "utf-8");

        PrintWriter pw = new PrintWriter(osw);

        pw.println("www");

        pw.println("ssss");

        pw.flush();
    }

    public static void mainRead(String[] args) throws IOException {
        //读取文件
        FileInputStream file = new FileInputStream("file.txt");

        int read = 0;
        while (read != -1) {
            read = file.read();
            System.out.print((char) read);
        }

        File file1 = new File("file.txt");

        FileInputStream file2 = new FileInputStream(file1);;

        byte[] content = new byte[1024];

        int bytes = file2.read(content);

        String s = new String(content, 0, bytes);

        System.out.println(s);

        //scanner
        try(InputStream in = new FileInputStream("file.txt")) {
            try(Scanner scanner = new Scanner(in)) {
                while (scanner.hasNext()) {
                    System.out.println(scanner.next());
                }
            }
        }
    }
}
